package com.realphim.app.component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.devsmart.android.ui.HorizontalListView;
import com.realphim.app.ActivityCategory;
import com.realphim.app.R;
import com.realphim.app.adapter.AdapterPhimCategory;
import com.realphim.app.model.ModelCategory;
import com.realphim.app.model.ModelPhim;
import com.realphim.app.util.CommonDefine;
import com.realphim.app.util.JSONParser;

public class LayoutCategory extends LinearLayout implements CommonDefine,
        OnClickListener {

    private Context context;

    private View mView;

    public String categoryName = "";

    public String urlGetPhim = "";

    public HorizontalListView lvCategory;

    public ProgressBar pbLoad;

    public RelativeLayout rlViewMore;

    public TextView tvCategoryName;

    public List<ModelPhim> listPhimCate;

    public AdapterPhimCategory adapterCate;

    public int pos_thumb = 0;

    private boolean isShowList = false;

    public LayoutCategory(Context context, String categoryName,
            String urlGetPhim) {
        super(context);
        this.context = context;
        this.categoryName = categoryName;
        this.urlGetPhim = urlGetPhim;
        this.listPhimCate = new ArrayList<ModelPhim>();
    }

    public void init() {
        try {
            if (mView == null) {

                // inflate layout
                LayoutInflater mLayoutInflater = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                mView = mLayoutInflater.inflate(R.layout.layout_category, null);

                lvCategory = (HorizontalListView) mView
                        .findViewById(R.id.lvCategory);

                pbLoad = (ProgressBar) mView.findViewById(R.id.pbLoad);

                rlViewMore = (RelativeLayout) mView
                        .findViewById(R.id.rlViewMore);

                tvCategoryName = (TextView) mView
                        .findViewById(R.id.tvCategoryName);

                rlViewMore.setOnClickListener(this);

                tvCategoryName.setOnClickListener(this);

                tvCategoryName.setText(categoryName);

                lvCategory.setVisibility(View.GONE);

                pbLoad.setVisibility(View.GONE);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        addView(mView, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.rlViewMore:
            Intent i = new Intent(context, ActivityCategory.class);
            i.putExtra(KeyBundle.CATEGORY_NAME,
                    getResources().getString(R.string.film_view_alot));
            i.putExtra(KeyBundle.URL_GET_PHIM, urlGetPhim);
            context.startActivity(i);
            ((Activity) context).overridePendingTransition(
                    R.anim.slide_in_left, R.anim.slide_out_left);
            break;
        case R.id.tvCategoryName:
            if (isShowList) {
                isShowList = false;
                lvCategory.setVisibility(View.GONE);

            } else {
                isShowList = true;
                lvCategory.setVisibility(View.VISIBLE);
                if (listPhimCate.size() == 0) {
                    pbLoad.setVisibility(View.VISIBLE);
                    new AsyncTaskGetListCate()
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            }
            break;
        }

    }

    private void showDialogNoConnection() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setTitle("Connection");
        dialog.setMessage("Can not connect to server");
        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private class AsyncTaskGetListCate extends
            AsyncTask<Integer, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(Integer... params) {
            boolean result = false;
            try {

                String strUrl = urlGetPhim
                        + "&"
                        + ServiceParam.LIMIT
                        + "="
                        + context.getResources().getInteger(
                                R.integer.item_in_home);
                Log.v(categoryName, strUrl);
                String jsonResult = new JSONParser().getJSONFromUrl(strUrl,
                        METHOD_GET, null);
                Log.i(categoryName, jsonResult);
                JSONArray arrResult = new JSONObject(jsonResult)
                        .getJSONArray("data");
                Log.v("JSON ARRAY LENGHT", "" + arrResult.length());
                for (int i = 0; i < arrResult.length(); i++) {
                    JSONObject objPhim = arrResult.getJSONObject(i);
                    ModelPhim myPhim = new ModelPhim();
                    myPhim.id = objPhim.getInt(KeyPhim.id);
                    myPhim.title = objPhim.getString(KeyPhim.title);
                    myPhim.titleTranslate = objPhim
                            .getString(KeyPhim.title_translate);
                    myPhim.imageUrl = objPhim.getString(KeyPhim.image);
                    myPhim.thumbnailUrl = objPhim.getString(KeyPhim.thumbnail);
                    myPhim.description = objPhim.getString(KeyPhim.description);
                    myPhim.lastEp = objPhim.getInt(KeyPhim.last_episode);
                    myPhim.maxEp = objPhim.getInt(KeyPhim.max_episode);
                    myPhim.isHD = objPhim.getInt(KeyPhim.is_hd);
                    myPhim.imb = objPhim.getString(KeyPhim.imdb);
                    myPhim.publishYear = objPhim
                            .getString(KeyPhim.publish_year);
                    myPhim.duration = objPhim.getInt(KeyPhim.duration);
                    myPhim.isFeature = objPhim.getInt(KeyPhim.is_featured);
                    myPhim.isCinema = objPhim.getInt(KeyPhim.is_cinema);
                    myPhim.rate = objPhim.getString(KeyPhim.rate);
                    myPhim.director = objPhim.getString(KeyPhim.director);
                    myPhim.viewFake = objPhim.getString(KeyPhim.view_fake);
                    myPhim.label = objPhim.getString(KeyPhim.label);
                    myPhim.actors = objPhim.getString(KeyPhim.actors);
                    myPhim.nation = objPhim.getString(KeyPhim.nation);
                    myPhim.tag = objPhim.getString(KeyPhim.tags);
                    myPhim.uploadBy = objPhim.getString(KeyPhim.upload_by);
                    myPhim.creatDate = objPhim.getString(KeyPhim.created_date);
                    myPhim.viewCount = objPhim.getString(KeyPhim.view_count);
                    myPhim.viewCountMonth = objPhim
                            .getString(KeyPhim.view_count_month);
                    myPhim.viewCountWeek = objPhim
                            .getString(KeyPhim.view_count_week);

                    JSONArray arrCategory = objPhim
                            .getJSONArray(KeyPhim.category);
                    for (int j = 0; j < arrCategory.length(); j++) {
                        JSONObject objCate = arrCategory.getJSONObject(j);
                        ModelCategory myCate = new ModelCategory();
                        myCate.id = objCate.getInt(KeyCategory.id);
                        myCate.title = objCate.getString(KeyCategory.title);
                        myPhim.listCategories.add(myCate);
                    }
                    listPhimCate.add(myPhim);
                    result = true;

                }
            } catch (JSONException e) {
                Log.e("ERROR", e.toString() + "");
                result = false;
            }
            return result;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            Log.v("Result " + categoryName, result + ":" + listPhimCate.size());
            if (result) {
                pbLoad.setVisibility(View.GONE);
                adapterCate = new AdapterPhimCategory(context, listPhimCate);
                lvCategory.setAdapter(adapterCate);
                if (listPhimCate.size() > 0) {
                    new AsyntaskLoadCover(0)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }

            } else {
                showDialogNoConnection();
            }
        }

    }

    private class AsyntaskLoadCover extends AsyncTask<String, String, Bitmap> {
        private int pos;

        public AsyntaskLoadCover(int pos) {
            this.pos = pos;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            // TODO Auto-generated method stub
            InputStream iStream = null;
            URL url;
            String name;
            try {
                url = new URL(listPhimCate.get(pos).thumbnailUrl);
                name = listPhimCate.get(pos).title;
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.connect();
                iStream = urlConnection.getInputStream();
                File cacheDirectory = context.getCacheDir();
                File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"
                        + name + ".png");
                FileOutputStream fOutStream = new FileOutputStream(tmpFile);
                Bitmap b = BitmapFactory.decodeStream(iStream);
                b.compress(Bitmap.CompressFormat.PNG, 100, fOutStream);

                Bitmap result = Bitmap.createScaledBitmap(b, 120, 180, true);
                fOutStream.flush();
                fOutStream.close();
                b.recycle();
                return result;

            } catch (Exception e) {
                Log.e("LoadImage", e.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            adapterCate.getItem(pos).thumbnailBitmap = result;
            adapterCate.notifyDataSetChanged();
            if (pos < adapterCate.getCount() - 1) {
                new AsyntaskLoadCover(pos + 1)
                        .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        }
    }

}
